import React from 'react';
import { Modal } from 'antd';

class DraggableModal extends React.Component {
  state = {
    position: { x: 0, y: 0 },
    isDragging: false,
    startPos: { x: 0, y: 0 }
  };

  modalRef = React.createRef();

  componentDidMount() {
    // 初始居中
    this.setInitialPosition();
  }

  componentDidUpdate(prevProps) {
    if (this.props.visible && !prevProps.visible) {
      this.setInitialPosition();
    }
  }

  setInitialPosition = () => {
    this.setState({
      position: { x: 0, y: 0 },
      isDragging: false
    });
  };

  handleMouseDown = (e) => {
    if (e.button !== 0) return;

    this.setState({
      isDragging: true,
      startPos: {
        x: e.clientX - this.state.position.x,
        y: e.clientY - this.state.position.y
      }
    });

    document.addEventListener('mousemove', this.handleMouseMove);
    document.addEventListener('mouseup', this.handleMouseUp);
  };

  handleMouseMove = (e) => {
    if (!this.state.isDragging) return;

    const x = e.clientX - this.state.startPos.x;
    const y = e.clientY - this.state.startPos.y;

    this.setState({
      position: { x, y }
    });
  };

  handleMouseUp = () => {
    this.setState({ isDragging: false });
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleMouseUp);
  };

  componentWillUnmount() {
    document.removeEventListener('mousemove', this.handleMouseMove);
    document.removeEventListener('mouseup', this.handleMouseUp);
  }

  render() {
    const { title, children, visible, onOk, onCancel, style, ...modalProps } = this.props;
    const { position, isDragging } = this.state;

    const modalStyle = {
      position: 'absolute',
      left: `calc(50% + ${position.x}px)`,
      top: `calc(50% + ${position.y}px)`,
      transform: 'translate(-50%, -50%)',
      margin: 0,
      ...style
    };

    const handleStyle = {
      cursor: isDragging ? 'grabbing' : 'grab',
      userSelect: 'none',
      padding: '16px 24px',
      margin: '-16px -24px 16px -24px',
      borderBottom: '1px solid #e8e8e8',
      backgroundColor: isDragging ? '#bae7ff' : '#e6f7ff',
      fontWeight: 'bold',
      transition: 'all 0.3s ease'
    };

    return (
      <Modal
        {...modalProps}
        visible={visible}
        onOk={onOk}
        onCancel={onCancel}
        style={modalStyle}
        title={
          <div
            style={handleStyle}
            onMouseDown={this.handleMouseDown}
          >
           {title}
          </div>
        }
      >
        {children}

      </Modal>
    );
  }
}

export default DraggableModal;
